package com.wisdom.utils;


import java.util.LinkedList;



import android.app.Activity;
import android.app.AlertDialog;
import android.app.AlertDialog.Builder;
import android.content.Context;
import android.content.DialogInterface;
import android.util.Log;
import android.widget.Toast;





public class ExitUtils 
{
	private static final LinkedList<Activity> sActivityList = new LinkedList<Activity>();
	private static boolean sProcessKilled = true;
	
	private ExitUtils() {} // no instance
	
	public static boolean isProcessKilled() 
	{
	    return sProcessKilled;
	}

	public static void setProcessStarted() 
	{
	    sProcessKilled = false;
	}
	
	/**
	 * 在每个Activity的onCreate中调用，用来记录打开了的activity
	 */
	public static void addActivity(Activity act) 
	{
		sActivityList.add(act);
	}
	
	/**
	 * 在每个Activity的onDestroy中调用
	 */
	public static void removeActivity(Activity act) 
	{
		sActivityList.remove(act);
	}
	
	/**
	 * 结束所有的activity，并关闭程序的进程
	 */
	public static void exit() 
	{
		finishAll();
		System.exit(0);
	}
	
	/**
	 * 结束所有的activity，但不会关闭程序的进程
	 */
	public static void finishAll() 
	{
	    for (Activity act : sActivityList) 
	    {
	    	Log.i("aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", act.toString());
            act.finish();
        }   
        sActivityList.clear();
	}
	
	
	
	/**
	 * 按对话框方式退出程序
	 */	
	public static void ExitWithDialog(Context context, String msg) 
	{ 
		AlertDialog.Builder builder = new Builder(context); 
		builder.setMessage(msg); 
		builder.setTitle("提示"); 
		builder.setPositiveButton("确认", new android.content.DialogInterface.OnClickListener() { 
			@Override 
			public void onClick(DialogInterface dialog, int which) { 
				dialog.dismiss();
				//context.finish();
				exit();
			} 
		});
			
		builder.setNegativeButton("取消", new android.content.DialogInterface.OnClickListener() { 
			@Override 
			public void onClick(DialogInterface dialog, int which) { 
				dialog.dismiss(); 
			} 
		}); 
		
		builder.create().show(); 
	}
	
	private static long exitTime = 0;
	/**
	 * 按点两次的方式退出程序
	 */		
	public static void ExitWithDoubleClick(Context context)
	{
		if ((System.currentTimeMillis() - exitTime) > 2000)
		{
			Toast.makeText(context, "再按一次退出程序", Toast.LENGTH_SHORT).show();
			exitTime = System.currentTimeMillis();
		} 
		else
		{
			exit();
		}

	}

}
